/*
 * dtim.c
 * Project 03
 * Nicole Ang (nang1@asu.edu)
 * Bijan Fakhri (bfakhri@asu.edu)
 * CSE325 Embedded Microprocessor Systems
 * Spring 2013
 */

#include "dtim.h"

/* Configures the appropriate DTIM0 registers to delay for 
 * p_usecs microseconds. */
void dtim0_delay(int p_usecs){
  //p_usecs is in milliseconds, convert to microseconds
  int usecs = p_usecs * 1000;
  
	//make counter start at 0
	MCF_DTIM0_DTCN = 0;
	
	//set reference value for delay
	//subtracting 1 b/c counter will increment once more before resetting
	MCF_DTIM0_DTRR = MCF_DTIM_DTRR_REF(usecs-1);
	
	//REF field: 1 = will clear event condition
	// will output reference event when counter = reference value
	MCF_DTIM0_DTER |= MCF_DTIM_DTER_REF;
	
	//start timer
	MCF_DTIM0_DTMR |= MCF_DTIM_DTMR_RST;
	
	//wait until reference event occurs, which signals end of delay
	while(!(MCF_DTIM0_DTER & 0x2)){}
}

/*Initializes the DTIM0 timer. */
void dtim0_init(){
	//RST field: 0 = reset and stop timer
	MCF_DTIM0_DTMR &= ~MCF_DTIM_DTMR_RST;
	
	//CLK field: 01 = internal bus clock divided by 1
	MCF_DTIM0_DTMR &= ~(MCF_DTIM_DTMR_CLK(3));//clear CLK field
	MCF_DTIM0_DTMR |= MCF_DTIM_DTMR_CLK(1);
	
	//FRR field: 1 reset timer when it reaches the reference value
	MCF_DTIM0_DTMR |= MCF_DTIM_DTMR_FRR;
	
	//ORRI field: 0 = disable interrupts
	MCF_DTIM0_DTMR &= ~MCF_DTIM_DTMR_ORRI;
	
	//00 = make timer in reference mode
	MCF_DTIM0_DTMR &= ~(MCF_DTIM_DTMR_CE(3)); //clear CE field
	
	//make clock counter increment every microsecond
	//80 / (79+1)
	MCF_DTIM0_DTMR &= ~(0xFF << 0x8); //clear PS field
	MCF_DTIM0_DTMR |= MCF_DTIM_DTMR_PS(79); //set PS field
	
	//DMAEN field: 0 = disable DMA request
	MCF_DTIM0_DTXMR &= ~MCF_DTIM_DTXMR_DMAEN;
	
	//HALTED field: 1 = stop counter when debugger stops
	MCF_DTIM0_DTXMR |= MCF_DTIM_DTXMR_HALTED;
	
	//MODE16 field: 0 = increment counter on clock pulse
	MCF_DTIM0_DTXMR &= ~MCF_DTIM_DTXMR_MODE16;
}